var JAToolbar = new Class({
	initialize: function(menu, options){
		this.options = $extend({
			holderID:	'jaToolbarHolder', //enable slide
			slide:	true, //enable slide
			duration: 300, //slide speed. lower for slower, bigger for faster
			fading: false, //Enable fading
			bgopacity: 0.9, //set the transparent background. 0 to disable, 0<bgopacity<1: the opacity of the background
			delayHide: 500,
			delayShowFistTime: 10000,
			position: 'bottom', //position of toolbar. 
			rtl: 0, //right to left mode
			direction: 'down',
			action: 'mouseenter', //mouseenter or click
			tips: true,	//enable jatooltips
			hidestyle: 'fastwhenshow',
			onLoad: null //Load done
		}, options || {});
		//adjust direction
		this.options.direction = (this.options.position=='bottom'?'up':'down');
		
		this.menu = menu;
		this.childopen = new Array();
		/*
		if (typeof(window.loaded) == 'undefined' || window.loaded) {
			this.imageloaded = false;
			this.start();
		} else {*/
			this.imageloaded = false;
			this.loaded = false;
			//window.addEvent('load', this.start.bind(this));
			this.start();
		//}
	},
	
	start: function () {
		//do nothing if loaded
		if (this.loaded) return;
		
		this.menu = $(this.menu);
		//preload images
		var images = this.menu.getElements ('img');
		if (images && images.length && !this.imageloaded) {
			var imgs = [];
			images.each (function (image) {imgs.push(image.src)});
			if (imgs.length) {
				new Asset.images(imgs, {			
					onComplete: function(){
						this.start();
					}.bind(this)
				});
				this.imageloaded = true;
				
				//call this start if cannot load image after sometime
				this.start.delay (3000, this);
				return ;
			}
		}
		clearTimeout (this.starttimeout);
		if (this.items) return; //started already
		this.items = this.menu.getElements ('li.tb');
		this.items.setStyle ('position', 'relative');
		this.items.each (function(li) {
			//link item
			if ((a = li.getElement('a.tb')) && this.isChild (a, li)) li.a = a;
			else li.a = null;
			//parent
			li._parent = this.getParent (li);
			//child content
			if ((childcontent = li.getElement('.childcontent')) && this.isChild (childcontent, li)) {
				li.childcontent = childcontent;
				li.childcontent_inner = li.childcontent.getElement ('.childcontent-inner-wrap');
				var coor = li.childcontent_inner.getCoordinates ();
				li._w = li.getElement('.childcontent-inner').offsetWidth;
				li._h = li.getElement('.childcontent-inner').offsetHeight;

				li.level0 = li.getParent().hasClass('level0');
				//
				//li.childcontent.setStyles ({'width':li._w+50, 'height':li._h});
				li.childcontent.setStyles ({'width':li._w+50});
				li.childcontent_inner.setStyles ({'width':li._w});
				//fix for overflow
				li.childcontent_inner1 = li.childcontent.getElement ('.childcontent-inner');
				li.childcontent_inner1.ol = false;
				if (li.childcontent_inner1.getStyle ('overflow') == 'auto' || li.childcontent_inner1.getStyle ('overflow') == 'scroll') {
					li.childcontent_inner1.ol = true;
					//fix for ie6/7
					if (window.ie6 || window.ie7) {
						li.childcontent_inner1.setStyle ('position', 'relative');
					}
					
					if (window.ie6) {
						li.childcontent_inner1.setStyle ('height', li.childcontent_inner1.getStyle ('max-height') || 400);
					}
				}

				//show direction
				if (this.options.direction == 'up') {
					if (li.level0) {
						//li.childcontent.setStyle ('top', -li.childcontent.offsetHeight); //ajust top position
						li.childcontent.setStyle ('bottom', li.offsetHeight);
					} else {
						li.childcontent.setStyle ('bottom', 0);
					}
				} else {
					//auto center if position of toolbar is top
					if (li.level0) {
					} else {
						li.addEvent("mouseenter", function(e){
							var lCoor = li.getCoordinates();
							//var cCoor = li.childcontent.getCoordinates();
							var wHeight = window.getHeight();
							
							var height = li.childcontent.getProperty('height');
							height = parseInt(height);
							
							if(lCoor.top > wHeight) {
								li.childcontent.setStyle ('bottom', 0);
							} else {
								if(lCoor.top + height > wHeight){
									while(lCoor.top + height > wHeight){
										height = height/2;
									}
									li.childcontent.setStyle ('bottom', -height);
								}
							}
						}.bind(this));
						
					}
				}
	
				if (li.level0) {
					//check position
					var lcor = li.getCoordinates();
					var ccor = li.childcontent.getCoordinates();
					var ml = 0;
					var l = lcor.left;
					var r = l + ccor.width;
					if (this.wrapper) {
						var wcor = this.wrapper.getCoordinates();
						l = l - wcor.left;
						r = wcor.right - r + 10;
					} else {
						r = window.getWidth() - r + 10;
					}
					if (l < 0 || l+r < 0) {
						ml = - l;
					} else if (r < 0) {
						ml = r;
					}
					if (ml != 0) li.childcontent.setStyle ('margin-left', ml);
/*					
					var pos = li.getPosition();
					var win = {'x': window.getWidth(), 'y': window.getHeight()};
					var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
					if (pos['x'] + li.childcontent.offsetWidth > win['x'] + scroll ['x']) li.childcontent.setStyle ('right', 0);
*/					
				} 
			}
			else li.childcontent = null;
			
			if (li.childcontent && this.options.bgopacity) {
				//Make transparent background
				var bg = new Element ('div', {'class':'childcontent-bg'});
				bg.injectTop (li.childcontent_inner);
				bg.setStyles ({'width':'100%', 'height':li._h, 'opacity':this.options.bgopacity,
								'position': 'absolute', 'top': 0, 'left': 0, 'z-index': 1
								});
				if (li.childcontent.getStyle('background')) bg.setStyle ('background', li.childcontent.getStyle('background'));
				if (li.childcontent.getStyle('background-image')) bg.setStyle ('background-image', li.childcontent.getStyle('background-image'));
				if (li.childcontent.getStyle('background-repeat')) bg.setStyle ('background-repeat', li.childcontent.getStyle('background-repeat'));
				if (li.childcontent.getStyle('background-color')) bg.setStyle ('background-color', li.childcontent.getStyle('background-color'));
				li.childcontent.setStyle ('background', 'none');
				li.childcontent_inner.setStyles ({'position':'relative', 'z-index': 2});
			}
			
			if (li.childcontent && (this.options.slide || this.options.fading)) {
				//li.childcontent.setStyles ({'width': li._w});
				li.childcontent.setStyles ({'left':'auto'});
				if (li.childcontent.hasClass ('right')) li.childcontent.setStyle ('right', 0);
				if (this.options.slide) {
					li.childcontent.setStyles ({'left':'auto', 'overflow':'hidden'});
					if (li.level0) {
						if (this.options.direction == 'up') {
							li.childcontent_inner.setStyle ('bottom', -li._h-20);
						} else {
							li.childcontent_inner.setStyle ('margin-top', -li._h-20);
						}
						
					} else {					
						li.childcontent_inner.setStyle ('margin-left', -li._w-20);
					}
				}
				if (this.options.fading) {
					li.childcontent_inner.setStyle ('opacity', 0);
				}
				//Init Fx.Styles for childcontent
				li.fx = new Fx.Styles(li.childcontent_inner, {duration: this.options.duration, transition: Fx.Transitions.linear, onComplete: this.itemAnimDone.bind(this, li)});
				//effect
				li.eff_on = {};
				li.eff_off = {};
				if (this.options.slide) {
					if (li.level0) {
						if (this.options.direction == 'up') {
							li.eff_on ['bottom'] = 0;
							li.eff_off ['bottom'] = -li._h;
						} else {
							li.eff_on ['margin-top'] = 0;
							li.eff_off ['margin-top'] = -li._h;
						}
					} else {						
						li.eff_on['margin-left'] = 0;
						li.eff_off['margin-left'] = -li._w;
					}
				}
				if (this.options.fading) {
					li.eff_on['opacity'] = 1;
					li.eff_off['opacity'] = 0;
					//li.eff_off['margin-top'] = -li._h;
				}
			}
				
			if (this.options.action=='click') {
				if (li.childcontent) {
					li.addEvent('click', function(e) {
						var event = new Event (e);
						if (li.hasClass ('group')) return;
						if (li.childcontent) {
							if (li.status == 'open') {
								if (this.cursorIn (li, event)) {
									this.itemHide (li);
								} else {
									this.itemHideOthers(li);
								}
							} else {
								this.itemShow (li);
							}
						} else {
							if (li.a) location.href = li.a.href;
						}
						event.stop();
					}.bind (this));
				
					//If action is click, click on windows will close all submenus
					this.windowClickFn = function (e) {		
						this.itemHideOthers(null);
					}.bind (this);
				}
				li.addEvent('mouseenter', function(e) {
					if (li.hasClass ('group')) return;
					this.itemOver (li);
					//e.stop();
				}.bind (this));
				
				li.addEvent('mouseleave', function(e) {
					if (li.hasClass ('group')) return;
					this.itemOut (li);
					//e.stop();
				}.bind (this));				
			}

			if (this.options.action == 'mouseover' || this.options.action == 'mouseenter') {
				li.addEvent('mouseenter', function(e) {
					if (li.hasClass ('group')) return;
					$clear (li.timer);
					this.itemShow (li);
					e.stop();
				}.bind (this));
				
				li.addEvent('mouseleave', function(e) {
					if (li.hasClass ('group')) return;
					$clear (li.timer);
					if (li.childcontent) li.timer = this.itemHide.delay(this.options.delayHide, this, [li, e]);
					else this.itemHide (li, e);
					e.stop();
				}.bind (this));
				
				//if has childcontent, don't goto link before open childcontent - fix for touch screen
				if (li.a && li.childcontent) {
					li.clickable = false;
					li.a.addEvent ('click',function (e){
						if (!li.clickable) {
							new Event(e).stop();
						}
					}.bind (this));
				}
				
			}
			
			//when click on a link - close all open childcontent
			if (li.a && !li.childcontent) {
				li.a.addEvent ('click',function (e){
					this.itemHideOthers (null);
					//Remove current class
					this.menu.getElements ('.active').removeClass ('active');
					//Add current class
					var p = li;
					while (p) {
						p.addClass ('active');
						p.a.addClass ('active');
						p = p._parent;
					}
					//new Event (e).stop();
				}.bind (this));
			}			
		},this);
		
		this.menu.getElements('.childcontent').each(function(childcontent){
			var coor = childcontent.getCoordinates();
			childcontent.setProperties({'width': coor.width, 'height': coor.height});
		});
		if (this.options.slide || this.options.fading) {
			//hide all content child
			this.menu.getElements('.childcontent').setStyle ('display', 'none');
		}
		
		//tooltips
		if (this.options.tips) {
			this.options.tips = this.buildTooltips ();
		}
		
		//Call onLoad
		if (typeof (this.options.onLoad) == 'function') this.options.onLoad.call (this);
	}, 
	
	getParent: function (li) { 
		var p = li;
		while ((p=p.getParent())) {
			if (this.items.contains (p) && !p.hasClass ('group')) return p;
			if (!p || p == this.menu) return null;
		}
	},
	
	cursorIn: function (el, event) {
		if (!el || !event) return false;
		var event = new Event(event);
		
		var pos = $merge (el.getPosition(), {'w':el.offsetWidth, 'h': el.offsetHeight});;
		//var cursor = {'x': event.page.x, 'y': event.page.y};
		var cursor = {'x': event.client.x, 'y': event.client.y};
		
		/*var content = 'cursor: x='+event.page.x+'; y='+event.page.y + '<br>';
		content += 'client: x='+event.client.x+'; y='+event.client.y + '<br>';
		content += 'pos: x='+pos.x+'; y='+pos.y + '<br>';
		$('test-position').setHTML(content);*/
	
		if (cursor.x>pos.x && cursor.x<pos.x+el.offsetWidth
				&& cursor.y>pos.y && cursor.y<pos.y+el.offsetHeight) return true;			
		return false;
	},
	
	isChild: function (child, parent) {
		return !!parent.getChildren().contains (child);
	},
	
	itemOver: function (li) {
		if (li.hasClass ('haschild')) 
			li.removeClass ('haschild').addClass ('haschild-over');
		li.addClass ('over');
		if (li.a) {
			li.a.addClass ('over');
		}
	},
	
	itemOut: function (li) {
		if (li.hasClass ('haschild-over'))
			li.removeClass ('haschild-over').addClass ('haschild');
		li.removeClass ('over');
		if (li.a) {
			li.a.removeClass ('over');
		}
	},

	itemShow: function (li) {		
		clearTimeout(li.timer);
		if (li.status == 'open') return; //don't need do anything
		//Setup the class
		this.itemOver (li);
		//Check if this is the first show
		if (li.childcontent) {
			var firstshow = true;
			this.childopen.each (function (li) {
				if (li.childcontent) firstshow = false;
			});
		}
		//push to show queue
		li.status = 'open';
		this.enableclick.delay (100, this, li);
		this.childopen.push (li);
		//hide other
		this.itemHideOthers (li);
		if (li.childcontent) {
			if (this.options.action=='click' && this.childopen.length && !this.windowClickEventAdded) {
				//addEvent click for window
				$(document.body).addEvent ('click', this.windowClickFn);
				this.windowClickEventAdded = true;
			}
		}
		
		if (!$defined(li.fx) || !$defined(li.childcontent)) return;
		
		li.childcontent.setStyle ('display', 'block');
		
		if (!li.level0) {
			//check if it's out of view-port
			var lcor = li.getCoordinates();
			var ccor = li.childcontent.getCoordinates();
			var ml = 0;
			var l = ccor.left;
			var r = l + ccor.width;
			if (this.wrapper) {
				var wcor = this.wrapper.getCoordinates();
				l = l - wcor.left;
				r = wcor.right - r + 10;
			} else {
				r = window.getWidth() - r + 10;
			}
			if (r < 0) {
				//change the direction and position for submenu
				li.childcontent.setStyle ('margin-left', -ccor.width + 20);
				li.eff_on['margin-left'] = 0;
				li.eff_off['margin-left'] = li._w + 20;
				li.childcontent_inner.setStyle ('margin-left', li.eff_off['margin-left']);
			}
		}
		
		li.childcontent.setStyles ({'overflow': 'hidden'});		
		if (li.childcontent_inner1.ol) li.childcontent_inner1.setStyles ({'overflow': 'hidden'});
		li.fx.stop();
		li.fx.start (li.eff_on);
		//disable tooltip for this item
		this.disableTooltip (li);
		//if (li._parent) this.itemShow (li._parent);
	},
	
	itemHide: function (li, e) {
		if (e && e.page) { //if event
			if (this.cursorIn (li, e) || this.cursorIn (li.childcontent, e)) {
				return;
			} //cursor in li
			var p=li._parent;
			if (p && !this.cursorIn (p, e) && !this.cursorIn(p.childcontent, e)) {
				p.fireEvent ('mouseleave', e); //fire mouseleave event
			}
		}
		clearTimeout(li.timer);
		this.itemOut(li);
		li.status = 'close';
		this.childopen.remove (li);
		if (li.childcontent) {
			if (this.options.action=='click' && !this.childopen.length && this.windowClickEventAdded) {
				//removeEvent click for window
				$(document.body).removeEvent ('click', this.windowClickFn);
				this.windowClickEventAdded = false;
			}
		}
		
		if (!$defined(li.fx) || !$defined(li.childcontent)) return;
		
		if (li.childcontent.getStyle ('opacity') == 0) return;
		li.childcontent.setStyles ({'overflow': 'hidden'});
		if (li.childcontent_inner1.ol) li.childcontent_inner1.setStyles ({'overflow': 'hidden'});
		li.fx.stop();
		switch (this.options.hidestyle) {
		case 'fast': 
			li.fx.options.duration = 100;
			li.fx.start ($merge(li.eff_off,{'opacity':0}));
			break;
		case 'fastwhenshow': //when other show
			if (!e) { //force hide, not because of event => hide fast
				//li.fx.options.duration = 300;
				li.fx.start ($merge(li.eff_off,{'opacity':0}));
			} else {	//hide as normal
				li.fx.start (li.eff_off);
			}
			break;
		case 'normal':
		default:
			li.fx.start (li.eff_off);
			break;
		}
		//li.fx.start (li.eff_off);		
	},
	
	itemAnimDone: function (li) {
		//hide done
		if (li.status == 'close'){
			//reset duration and enable opacity if not fading
			if (this.options.hidestyle.test (/fast/)) {
				li.fx.options.duration = this.options.duration;
				if (!this.options.fading) li.childcontent_inner.setStyle ('opacity', 1);
			}
			//hide
			li.childcontent.setStyles ({'display': 'none'});
			//enable tooltip
			this.enableTooltip (li);
			//call event
			if (typeof (this.options.onItemHideComplete) == 'function') this.options.onItemHideComplete.call (this, li);
			//Check if there's no child content shown, raise event onLastHide
			var lasthide = true;
			this.childopen.each (function (li) {
				if (li.childcontent) lasthide = false;
			});
			if (lasthide && typeof (this.options.onLastHide) == 'function') this.options.onLastHide.call (this, li);
		}
		
		//show done
		if (li.status == 'open'){
			li.childcontent.setStyles ({'overflow': ''});
			if (li.childcontent_inner1.ol) li.childcontent_inner1.setStyles ({'overflow-y': 'auto'});
		}
	},
	
	itemHideOthers: function (el) {
		var fakeevent = null
		if (el && !el.childcontent) fakeevent = {};
		var curopen = this.childopen.copy();
		curopen.each (function(li) {
			if (li && typeof (li.status) != 'undefined' && (!el || (li != el && !li.hasChild (el)))) {
				this.itemHide(li, fakeevent);
			}
		},this);
	},

	buildTooltips: function () {
		this.tooltips = new JAToolbarTips (this.menu.getElements ('.hasTipThumb'), {'className':'ja-toolbar-thumb', 'fixed':true, offsets:{'x':100, 'y': this.options.direction=='up'?-180:20}, 'direction': this.options.direction});
		this.tooltips2 = new JAToolbarTips (this.menu.getElements ('.hasTipThumb2'), {'className':'ja-toolbar-thumb2', 'fixed':true, offsets:{'x':100, 'y': 20}, 'direction': this.options.direction});
		this.tooltips3 = new JAToolbarTips (this.menu.getElements ('.hasTipThumb3'), {'className':'ja-toolbar-thumb3', 'fixed':true, offsets:{'x':100, 'y': 20}, 'direction': this.options.direction});
		return true;
	},
	
	disableTooltip: function (el) {
		if (this.options.tips) this.tooltips.disableTip(el);
		return;
	},
	
	enableTooltip: function (el) {
		if (this.options.tips) this.tooltips.enableTip(el);
		return;
	},

	enableclick: function (li) {
		if (li.a && li.childcontent) li.clickable = true;
	},
	disableclick: function (li) {
		if (li.a && li.childcontent) li.clickable = false;
	}
});

//Show / hide toolbar
JAToolbar.prototype.show = function () {
	this.toolbar.fireEvent ('beforeShow');
	this.status = 'show';
	this.fx.stop();
	//this.toolbar.setStyle ('overflow', 'hidden');
	if (this.options.direction == 'up') 
		this.fx.start ({'bottom':0});
	else
		this.fx.start ({'margin-top':0});
}

JAToolbar.prototype.hide = function () {
	this.toolbar.fireEvent ('beforeHide');	
	this.status = 'hide';
	this.fx.stop();
	//this.toolbar.setStyle ('overflow', 'hidden');
	if (this.options.direction == 'up') {
		this.fx.start ({'bottom':-this._h[this.options.mode]});
	} else {
		this.fx.start ({'margin-top':-this._h[this.options.mode]});
	}
}

//
JAToolbar.prototype.showhideDone = function () {
	this.toolbar.removeClass (this.options.mode);	
	if (this.status == 'show') {
		if (this.options.onCompletedShow) this.options.onCompletedShow.call(this);
		//this.toolbar.setStyles ({'overflow': ''});
		this.toolbar.fireEvent ('show');
	}
	if (this.status == 'hide') {
		if (this.options.onCompletedHide) this.options.onCompletedHide.call(this);
		this.toolbar.fireEvent ('hide');
	}
	this.toolbar.addClass (this.options.mode);
}

//
JAToolbar.prototype.toggle = function () {
	this.options.onCompletedHide = function () {
		if (this.options.mode == 'full') {
			this.options.mode = 'compact';
			//toogle
			this.toolbar_full.setStyle ('display', 'none');
			this.toolbar_compact.setStyle ('display', 'block');
			//resize main page' height
			$(this.options.holderID).setStyle('padding-top', '0px');
		} else {
			this.options.mode = 'full';
			//toogle
			this.toolbar_full.setStyle ('display', 'block');
			this.toolbar_compact.setStyle ('display', 'none');
			//resize main page' height
			$(this.options.holderID).setStyle('padding-top', this._h ['full'] + 'px');
		//	var myFx = new Fx.Scroll(window).toBottom();
		}		
		this.show();
		//Set cookie
		Cookie.set ('jatoolbar_mode', this.options.mode, {'path':'/', 'duration': 3});
	}
	this.hide ();
}
//Init for toolbar and showup
JAToolbar.prototype.display = function (options) {
	this.options = Object.extend(this.options, options || {});
	this.toolbar = $('ja-toolbar');
	this.toolbar_full = $('ja-toolbar-main');
	this.toolbar_compact = $('ja-toolbar-compact');
	this.toolbar_toggle = $('ja-toolbar-toggle');
	
	if (Cookie.get ('jatoolbar_mode')) this.options.mode = Cookie.get ('jatoolbar_mode');
	if (!this.options.mode) this.options.mode = 'full';
	if(this.options.mode == 'full' && !Cookie.get ('jatoolbar_mode')) {
		// delay when view full mode on first time
		this.options.mode = 'compact';
		var isFirstTime = 1;
	} else {
		var isFirstTime = 0;
	}
	this.toolbar.addClass (this.options.mode);
	
	this._h = {'full':50, 'compact':30};
	this._h ['full'] = Math.max (this.toolbar_full.offsetHeight, this.toolbar_toggle.offsetHeight);
	this._h ['compact'] = Math.max (this.toolbar_compact.offsetHeight, this.toolbar_toggle.offsetHeight);
	this.fx = new Fx.Styles (this.toolbar, {'duration': this.options.duration,'onComplete': this.showhideDone.bind(this)});
	
	if (this.options.mode == 'full') {
		this.toolbar_full.setStyle ('display', 'block');
		this.toolbar_compact.setStyle ('display', 'none');
		$(this.options.holderID).setStyle('padding-top', this._h ['full'] + 'px');
	} else {
		this.toolbar_full.setStyle ('display', 'none');
		this.toolbar_compact.setStyle ('display', 'block');
		$(this.options.holderID).setStyle('padding-top', '0px');
		if(isFirstTime) {
			setTimeout("megatoolbar.toggle();", this.options.delayShowFistTime);
		}
	}
	
	//Hide toolbar at first
	//this.toolbar.setStyles ({'overflow':'hidden'});
	if (this.options.direction == 'up') {
		this.toolbar.setStyles({'bottom':-this._h[this.options.mode]});
	} else {
		this.toolbar.setStyles ({'margin-top':-this._h[this.options.mode]});
	}
	
	this.toolbar_toggle.addEvent ('click', function (){this.toggle()}.bind(this));
	this.toolbar.setStyle ('visibility', 'visible');
	this.show.delay(1000, this);
	
	//for dim background
	if (this.options.overlay) {
		var w = window.getWidth()?window.getWidth():window.innerWidth;
		var h = window.getHeight()?window.getHeight():window.innerHeight;
		this.overlay = new Element ('div', {'id': 'jatoolbar-overlay'}).inject (document.body);
		this.overlay.setStyles ({'width':w, 'height': h, 'position': 'absolute', 'top':0, 'left':0, 'z-index': 999, 'opacity': 0, 'display': 'none', 'background': '#000'});
		this.toolbar.setStyle ('z-index', 1000);
		this.overlay.status = 'hide';
		this.overlay.fx = new Fx.Styles (this.overlay, {onComplete: function(){if (this.overlay.status=='hide'){this.overlay.setStyle('display', 'none');}}.bind(this)});
		this.options.onFirstShow = function () {
			if (this.overlay.status == 'hide') {
				//show overlay
				this.overlay.status = 'show';
				this.overlay.setStyle ('display','block');
				this.overlay.fx.stop();
				this.overlay.fx.start ({'opacity':this.options.overlay});
			}
		};
		this.options.onLastHide = function () {
			if (this.overlay.status == 'show') {
				//show overlay
				this.overlay.status = 'hide';
				this.overlay.fx.stop();
				this.overlay.fx.start ({'opacity':0});
			}
		};
	}
}

//Overwrite Tips class

var JAToolbarTips = new Class({

	options: {
		onShow: function(tip){
			tip.setStyle('visibility', 'visible');
		},
		onHide: function(tip){
			tip.setStyle('visibility', 'hidden');
		},
		maxTitleChars: 30,
		showDelay: 100,
		hideDelay: 100,
		className: 'tool',
		offsets: {'x': 16, 'y': 16},
		fixed: false
	},

	initialize: function(elements, options){
		this.setOptions(options);
		this.options.timeout = 0; //no timeout
		this.toolTip = new Element('div', {
			'class': this.options.className + '-tip',
			'styles': {
				'position': window.ie6?'absolute':'fixed',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		this.wrapper = new Element('div').inject(this.toolTip);
		$$(elements).each(this.build, this);
		if (this.options.initialize) this.options.initialize.call(this);
		this.toolTip.addEvent ('mouseenter', function(event) { 
			this.start(this.curTip); event.stop();
			this.curTip.fireEvent ('mouseenter', event);
		}.bind(this));
		this.toolTip.addEvent ('mouseleave', function (event) {
			this.end(event);
			this.curTip.fireEvent ('mouseleave', event);
		}.bind (this));
	},

	build: function(el){
		var myTitle = (el.href && el.getTag() == 'a') ? el.href.replace('http://', '') : (el.rel || false);
		var myText;
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1){
				myTitle = dual[0].trim();
				myText = dual[1].trim();
			} else {
				myText = el.title;
			}
			el.removeAttribute('title');
		} else {
			myText = '';
		}
		if (myTitle && myTitle.length > this.options.maxTitleChars) myTitle = myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		
		el.setProperties({'myTitle': myTitle, 'myText': myText});
		
		el.addEvent('mouseenter', function(event){
			this.start(el);
			if (!this.options.fixed) this.locate(event);
			else this.position(el);
		}.bind(this));
		if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
		var end = this.end.bind(this);
		el.addEvent('mouseleave', end);
		el.addEvent('trash', end);
	},

	start: function(el){
		if (!el) el = this.curTip;
		//Add status to disable tips
		if (el.tip && el.tip == 'disabled') return;
		var myText = el.getProperty('myText');
		var myTitle = el.getProperty('myTitle');
		if (myText == '') return; //blank tip
		this.curTip = el;
		//Original code
		this.wrapper.empty();
		if (myTitle){
			this.title = new Element('span').inject(new Element('div', {'class': this.options.className + '-title'}).inject(this.wrapper)).setHTML(myTitle);
		}
		if (myText){
			this.text = new Element('span').inject(new Element('div', {'class': this.options.className + '-text'}).inject(this.wrapper)).setHTML(myText);
		}
		$clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
	},

	end: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},

	position: function(element){
		var eCoor = element.getCoordinates();
		var tCoor = this.toolTip.getCoordinates();
		var left = eCoor.left + this.options.offsets.x;
		if(this.options.direction == 'down') {
			var top = eCoor.top - tCoor.height;
		} else {
			var top = eCoor.top + this.options.offsets.y;
		}
		
		if(left + tCoor.width > window.getWidth()) left = eCoor.left - tCoor.width;// - this.options.offsets.x
		if(top < 5) top = 5;//eCoor.top - tCoor.height - this.options.offsets.y;
		this.toolTip.setStyles({
			'left': left,
			'top': top
		});
	},

	locate: function(event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.toolTip.setStyle(prop[z], pos);
		};
	},

	show: function(){
		if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
		this.fireEvent('onShow', [this.toolTip]);
	},

	hide: function(){
		this.fireEvent('onHide', [this.toolTip]);
	},
	
	enableTip: function(el){
		if (el) el.tip = 'enabled';
	},
	
	disableTip: function(el){
		if (el) el.tip = 'disabled';
		if (this.curTip && this.curTip == el) this.hide();
	}

});

JAToolbarTips.implement(new Events, new Options);
